package com.kmxd.ams.core.util;

import static com.kmxd.ams.core.common.constant.RoleConst.ROLE_ARCH_ADMIN_CODE;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.kmxd.ams.core.common.bo.LoginUser;
import com.kmxd.ams.core.common.bo.SysRoleBO;
import com.kmxd.ams.core.common.bo.SysUserBO;
import com.kmxd.ams.core.common.constant.Constants;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.exception.BizException;
import com.kmxd.ams.core.exception.LogInfo;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;

/**
 * 安全服务工具类
 *
 * @author admin
 */
@Slf4j
public class SecurityUtil {
  /** 获取用户账户 */
  public static String getUsername() {
    return getLoginUser().getUsername();
  }

  public static String getRealname() {
    return getLoginUser().getRealName();
  }

  public static String getUsername(String token) {
    return getLoginUser(token).getUsername();
  }
  /** 获取系统用户 */
  public static SysUserBO getSysUser() {
    return getLoginUser().getSysUser();
  }

  /** 获取用户 */
  public static LoginUser getLoginUser() {
    try {
      return (LoginUser) StpUtil.getTokenSession().get(Constants.LOGIN_USER_KEY);
    } catch (Exception ex) {
      return null;
    }
  }

  /** 获取用户 */
  public static LoginUser getLoginUser(String token) {
    try {
      return (LoginUser) StpUtil.getTokenSessionByToken(token).get(Constants.LOGIN_USER_KEY);
    } catch (Exception ex) {
      return null;
    }
  }

  public static Long getUserId() {
    LoginUser loginUser =
        Optional.ofNullable(getLoginUser())
            .orElseThrow(() -> new BizException(LogInfo.newInstance(), ErrorCode.USER_NOT_FOUND));
    return java.lang.Long.valueOf(loginUser.getUserId());
  }

  public static Long getUserId(String token) {
    LoginUser loginUser =
        Optional.ofNullable(getLoginUser(token))
            .orElseThrow(() -> new BizException(LogInfo.newInstance(), ErrorCode.USER_NOT_FOUND));
    return java.lang.Long.valueOf(loginUser.getUserId());
  }

  /** 当前单位Id */
  public static Long getCropId() {
    LoginUser currentUser = getLoginUser();
    if (Objects.isNull(currentUser)) {
      return null;
    }
    return currentUser.getCropId();
  }

  /** 当前单位Id */
  public static Long getCropId(String token) {
    LoginUser currentUser = getLoginUser(token);
    if (Objects.isNull(currentUser)) {
      return null;
    }
    return currentUser.getCropId();
  }

  /** 当前单位名称 */
  public static String getCropName() {
    LoginUser currentUser = getLoginUser();
    if (Objects.isNull(currentUser)) {
      return null;
    }
    return currentUser.getCropName();
  }

  /** 当前全宗Id */
  public static Long getFondsId() {
    LoginUser currentUser = getLoginUser();
    if (Objects.isNull(currentUser)) {
      return null;
    }
    return currentUser.getFondsId();
  }

  public static Long getFondsId(String token) {
    LoginUser currentUser = getLoginUser(token);
    if (Objects.isNull(currentUser)) {
      return null;
    }
    return currentUser.getFondsId();
  }
  /** 当前全宗Code */
  public static String getFondsCode() {
    LoginUser currentUser = getLoginUser();
    if (Objects.isNull(currentUser)) {
      return null;
    }
    return currentUser.getFondsCode();
  }
  /** 当前全宗名称 */
  public static String getFondsName() {
    LoginUser currentUser = getLoginUser();
    if (Objects.isNull(currentUser)) {
      return null;
    }
    return currentUser.getFondsName();
  }

  /** 当前全宗自增序号-自增序号用于切换电子文件表 */
  public static Integer getindexNum() {
    return ObjectUtil.isNotEmpty(getLoginUser()) ? getLoginUser().getIndexNum() : null;
  }

  /** 是否是超级管理员 */
  public static Boolean isRootGroup(Set<String> roles) {
    if (CollUtil.isEmpty(roles)) {
      return Boolean.FALSE;
    }
    return roles.contains(Constants.ROOT_GROUP);
  }

  /** 是否是超级管理员 */
  public static Boolean isRootGroup() {
    return isRootGroup(
        getSysUser().getRoles().stream().map(SysRoleBO::getRoleCode).collect(Collectors.toSet()));
  }

  /**
   * 判断当前用户是否是档案管理员
   *
   * @param comCode
   * @return
   */
  public static Boolean isArchAdmin(String comCode) {
    String code = StrUtil.format(ROLE_ARCH_ADMIN_CODE, comCode);
    List<String> roles =
        getSysUser().getRoles().stream().map(SysRoleBO::getRoleCode).collect(Collectors.toList());
    return roles.contains(code);
  }

  /**
   * 判断
   *
   * @param comCode
   * @param userBO
   * @return
   */
  public static Boolean isArchAdmin(String comCode, SysUserBO userBO) {
    if (ObjectUtil.isEmpty(userBO)) {
      return Boolean.FALSE;
    }
    String code = StrUtil.format(ROLE_ARCH_ADMIN_CODE, comCode);
    List<String> roles =
        userBO.getRoles().stream().map(SysRoleBO::getRoleCode).collect(Collectors.toList());
    return roles.contains(code);
  }

  /** 是否是超级管理员 */
  public static Boolean isRootGroup(Long userId) {
    return Objects.nonNull(userId) && userId == 88L;
  }

  /**
   * 生成BCryptPasswordEncoder密码
   *
   * @param password 密码
   * @return 加密字符串
   */
  public static String encryptPassword(String password) {
    return BCrypt.hashpw(password);
  }

  /**
   * 判断密码是否相同
   *
   * @param rawPassword 真实密码
   * @param encodedPassword 加密后字符
   * @return 结果
   */
  public static boolean matchesPassword(String rawPassword, String encodedPassword) {
    return BCrypt.checkpw(rawPassword, encodedPassword);
  }

  public static String getTokenValue() {
    try {
      return StpUtil.getTokenValue();
    } catch (Exception e) {
      log.debug("获取getTokenValue异常：{}", e.getMessage());
      return "";
    }
  }

  /**
   * 获取登录用户的 语言信息
   *
   * @return 语言信息
   */
  public static String getLangCode() {
    LoginUser loginUser = SecurityUtil.getLoginUser();
    if (Objects.isNull(loginUser)) {
      return Constants.DEFAULT_LANG_CODE;
    }
    String langCode = loginUser.getLangCode();
    return StrUtil.isBlank(langCode) ? Constants.DEFAULT_LANG_CODE : langCode;
  }

  public static Integer getRoleType() {
    try {
      LoginUser loginUser = SecurityUtil.getLoginUser();
      return ObjectUtil.isEmpty(loginUser) ? null : loginUser.getRoleType();
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }

  public static Integer getRoleType(String token) {
    try {
      LoginUser loginUser = SecurityUtil.getLoginUser(token);
      return loginUser.getRoleType();
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }

  public static Long getRoleId() {
    try {
      LoginUser loginUser = SecurityUtil.getLoginUser();
      return loginUser.getRoleId();
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }

  public static Long getRoleId(String token) {
    try {
      LoginUser loginUser = SecurityUtil.getLoginUser(token);
      return loginUser.getRoleId();
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }

  /**
   * 根据当前角色返回管理状态
   *
   * @return
   */
  public static Long getManageStatus() {
    try {
      Integer roleType = getRoleType();
      return ObjectUtil.isNotEmpty(roleType) ? (long) roleType : null;
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }

  public static Long getManageStatus(String saToken) {
    try {
      Integer roleType = getRoleType();
      return ObjectUtil.isNotEmpty(roleType) ? (long) roleType : null;
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }
}
